package com.hwd.srb.sms.controller.api;

import com.hwd.srb.common.constant.OssConstants;
import com.hwd.srb.common.exception.BusinessException;
import com.hwd.srb.common.result.R;
import com.hwd.srb.common.result.ResponseEnum;
import com.hwd.srb.sms.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 黄伟东/Victor
 * @date 2022/3/16 14:58
 * @Description
 */
@RestController
@RequestMapping("/api/oss/file")
@ApiModel("后台阿里云文件管理接口")
@Api(tags = "阿里云文件管理")
@Slf4j
public class ApiOssController {

    @Resource
    private FileService fileService;

    @DeleteMapping("/remove")
    @ApiOperation("文件删除")
    public R remove(@ApiParam(value = "删除文件的url", required = true) @RequestParam("url") String url) {

        // 调用业务层方法执行文件删除
        fileService.removeFile(url);
        return R.ok().message(OssConstants.REMOVE_FILE_SUCCESS);
    }

    /**
     * 文件上传
     *
     * @param multipartFile 文件对象
     * @param module        模块名
     * @return com.hwd.srb.common.result.R
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传")
    public R upload(
            @ApiParam(value = "上传的文件", required = true)
            @RequestParam("file") MultipartFile multipartFile,
            @ApiParam(value = "模块", required = true)
            @RequestParam("module") String module) {

        try {
            InputStream inputStream = multipartFile.getInputStream();
            String originalFilename = multipartFile.getOriginalFilename();

            // 调用业务层方法上传文件
            String uploadUrl = fileService.upload(inputStream, module, originalFilename);

            return R.ok().message(OssConstants.UPLOAD_FILE_SUCCESS).data(OssConstants.UPLOAD_URL, uploadUrl);

        } catch (IOException e) {
            log.error(ResponseEnum.UPLOAD_ERROR.getMessage());
            log.error("异常信息:{}", e.getMessage());
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
        }


    }

}
